var crypto = require("crypto");
var fs = require("fs");
var path = require("path");

/**
 * sort排列对象，对象比较函数
 * @param filed
 * @param order desc | asc
 * @returns {Function}
 */
exports.compareObjectFn = function(filed,order){
    order = order==undefined ? 'asc' : order.toLowerCase();
    return function(obj,obj2){
        console.log(order);
        if(obj[filed]>obj2[filed]){
            if(order=="asc"){
                return 1;
            }else{
                return -1;
            }
        }else if(obj[filed]==obj2[filed]){
            return 0;
        }else{
            if(order=="asc"){
                return -1
            }else{
                return 1;
            }
        }
    }
}

/**
 * 深度克隆对象，两个对象互不影响
 * @param Obj
 * @returns {*}
 */
exports.clone=function(Obj){
    var buf;
    if (Obj instanceof Array) {
        buf = [];  //创建一个空的数组
        var i = Obj.length;
        while (i--) {
            buf[i] = this.clone(Obj[i]);
        }
        return buf;
    }else if (Obj instanceof Object){
        buf = {};  //创建一个空对象
        for (var k in Obj) {  //为这个对象添加新的属性
            buf[k] = this.clone(Obj[k]);
        }
        return buf;
    }else{
        return Obj;
    }
}

/**
 * 随机字符串
 * @returns {string}
 */
exports.s8=function(){
    var a = Math.round(4294967295 * Math.random()).toString(16);
    for (var b = a.length; b < 8; b++)
        a = '0' + a;
    return a.toLowerCase();
}

exports.md5 = function(buffer_data){
    var hasher=crypto.createHash("md5");
    m = hasher.update(buffer_data);
    var hashmsg=hasher.digest('hex');
    return hashmsg;
}

exports.replaceAll = function(str,search,replace){
    return str.replace(new RegExp(search,"gm"),replace);
}

/**
 * 合并两个对象
 * @param obj
 * @param obj2
 * @returns {*}
 */
exports.merge = function(obj,obj2){
    if(typeof  obj!="object"){
        obj = {};
    }
    if(typeof  obj2!="object"){
        obj2 = {};
    }
    for(var i in obj2){
        obj[i] = obj2[i];
    }
    return obj;
}

/**
 * 创建目录
 * @param dir
 */
exports.mkdir = function(dir){
    var mkdirAr = [];
    for(var i=0;i<100;i++){
        if(!fs.existsSync(dir)){
            mkdirAr.unshift(dir);
        }else{
            break;
        }
        dir = path.dirname(dir);
    }
    var len = mkdirAr.length;
    for(var i=0;i<len;i++){
        fs.mkdirSync(mkdirAr[i]);
    }
}